import * as service from '../services/ModuleServices';

export default {
  namespace: 'Module',
  state: {
    datas: [],
    pageSize: null,
    pageNumber: null,
    totalPage: null
  },
  reducers: {
    empty(state) {
      debugger;
      return {...state, datas: [], pageSize: null, pageNumber: null, totalPage: null};
    },
    save(state, {payload: {datas, pageSize, pageNumber, totalPage}}) {
      debugger;
      return {...state, datas, pageSize, pageNumber, totalPage};
    },
  },
  effects: {
    *fetch({payload: {pageNumber = 1}}, {call, put}) {
      debugger;
      const json = yield call(service.fetch, {pageNumber});
      if (null == json) {
        debugger;
        yield put({type: 'empty'});
      } else {
        debugger;
        yield put({type: 'save', payload: json});
      }
    },
    *add(values, {call, put, select}){
      debugger;
      yield call(service.add, values);
      const {pageNumber, pageSize} = yield select(state => state.Module); // 从state获取原来的分页数据
      yield put({type: 'fetch', payload: {pageNumber, pageSize}});
    },
    *edit(values, {call, put, select}){
      debugger;
      yield call(service.edit, values);
      const {pageNumber, pageSize} = yield select(state => state.Module); // 从state获取原来的分页数据
      yield put({type: 'fetch', payload: {pageNumber, pageSize}});
    },
    *del(values, {call, put, select}){
      debugger;
      yield call(service.del, values);
      const {pageNumber, pageSize} = yield select(state => state.Module); // 从state获取原来的分页数据
      yield put({type: 'fetch', payload: {pageNumber, pageSize}});
    },
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(
        ({pathname, query = {pageNumber: 1}}) => {
          debugger;
          if (pathname === '/module') {
            debugger;
            dispatch({type: 'fetch', payload: query});
          }
          ;
        },
      );
    },
  },
};
